const express = require("express");
const bodyParser = require("body-parser");
const http = require('http');
const { connectDB } = require("./db");


class Server {
    constructor() {
        this.app = express();

        this.app.use(bodyParser.urlencoded({ extended: false }));
        this.app.use(bodyParser.json());

        this.server = http.createServer(this.app);
    }
    
    setRoute(routeOption) {

        const method = routeOption.method ?? 'post';
        const handler = async (req, res) => {
            // 合并参数
            const event = Object.assign(req.body, req.query, req.params);
            let result;
            try {
                result = await routeOption.handle(event, req, res);
                result = {
                    code: 0,
                    data: result
                }
            }
            catch(e) {
                console.error(`request path ${req.path} error`, e);
                result = {
                    code: 500,
                    data: null,
                    message: e.message
                }
            }
            res.send(result);
        }
        this.app[method](routeOption.path, handler);
        
    }


    listen(port) {
        this.port = port;
        this.server.listen(this.port, () => {
            console.log(`server start at ${this.port}`);
        });
    }
}


module.exports = Server;

